<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: luchao@clcw.com.cn                                             |
// +------------------------------------------------------------------------+
//
/**
 * 抽奖活动
 */
namespace AuctionBack\Controller;

use AuctionCore\CarDealer\Dealer;
use AuctionCore\System\AuctionException;
use AuctionCore\Account\Back\Employee;

class RaffleController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
        //分公司
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
    }

    public function index()
    {   
        $this->display();
    }

    //活动列表
    public function raffle_list()
    {   
        $page = I("get.p", 1);
        $bc_city = I('request.bc_city');
        $size = 10;
        $params = array();
        $params['start_time'] = I("get.start_time");
        $params['end_time'] = I("get.end_time");
        $params['keyword'] = urldecode(I("get.keyword"));
        $params['bc_city'] = I("get.bc_city");
        //获取list
        $ol = new \AuctionCore\Other\RaffleList();
        $result = $ol->getList($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show();// 分页显示输出
        $this->assign('page', $show);// 赋值分页输出
        $this->assign('list', $result['list']);
        // $rules = "ZhuiJiaHuoDongJinE";
        // $e = new Employee($this->user_info['username']);
        // $auth = $e->check_auth($rules);
        // $this->assign('auth', $auth);
        $this->display();
    }

    //追加活动金额
    public function add_activity_amount()
    {
        $a_id = I('post.a_id');
        $amount= trim(I('post.amount'));
        if($a_id<1){
            $this->helpJsonResult('401',"活动id有误");
        }
        $code = '200';
        $msg = 'SUCCESS';
        try {
            $Raffle = new \AuctionCore\Other\Raffle();
            $res = $Raffle->add_activity_amount($a_id,$amount);
        }
        catch (AuctionException $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        $this->helpJsonResult($code, $msg);
    }
    //新增活动
    public function add_raffle(){
        $code = '200';
        $msg = 'SUCCESS';
        $a_name = trim(I('post.rafflename'));
        $amount = trim(I('post.amount'));
        $start_date = trim(I('post.start_date'));
        $end_date = trim(I('post.end_date'));
        $type = trim(I('post.type'));
        $form = trim(I('post.form'));
        $coupon_end_date = trim(I('post.coupon_end_date'));
        $bc_city = trim(I('post.bc_city'));
        if (empty($a_name)) {
            $code = '532';
            $msg = '活动名称不能为空';
        }
        if (empty($amount)) {
            $code = '533';
            $msg = '活动金额不能为空';
        }
        if (empty($type)) {
            $code = '533';
            $msg = '活动类型不能为空';
        }
        if (empty($form)) {
            $code = '533';
            $msg = '活动形式不能为空';
        }
        if (empty($start_date)) {
            $code = '534';
            $msg = '活动开始日期不能为空';
        }
        if (empty($end_date)) {
            $code = '535';
            $msg = '活动结束日期不能为空';
        }
        if ($type == 2 && empty($coupon_end_date)) {
            $code = '535';
            $msg = '代金券截止日期不能为空';
        }
        if (empty($bc_city)) {
            $code = '537';
            $msg = '活动所属公司不能为空';
        }
        $is_exist = M('activity')->where("a_name='$a_name'")->find();
        if (!empty($is_exist)) {
            $code = '536';
            $msg = '活动名称已存在';
        }
        //一个时间段只能存在一个活动
        $where = "((`starttime`>= '".$start_date."' and `starttime` <= '".$end_date."') or (`endtime` >='".$start_date."' and `endtime`<= '".$end_date."') or (`starttime`<= '".$start_date."' and `endtime` >= '".$end_date."')) and `type` = '".$type."'  and `branch_id` = '".$bc_city."'";
        $is_exist1 = M('activity')->where($where)->find(); 
        if (!empty($is_exist1)) {
            $code = '537';
            $msg = '当前时间范围内已存在另外一个活动';
        }
        if ($code == '200') {
            $data = array();
            $data['emp_id'] = $this->emp_id;
            $data['a_name'] = $a_name;
            $data['amount'] = $amount;
            $data['start_date'] = $start_date;
            $data['end_date'] = $end_date;
            $data['bc_city'] = $bc_city;
            $data['form'] = $form;
            $data['type'] = $type;
            if ($type == 2) {
                $data['coupon_end_date'] = $coupon_end_date;
            }
            //面值 目前是不可维护的 
            $denomination = array('100','300','500','1000','2000');
            $data['denomination'] = json_encode($denomination);
            $res = false;
            try {
                $Raffle = new \AuctionCore\Other\Raffle();
                $res = $Raffle->add($data);
            } catch (AuctionException $e) {
                $code = $e->getCode();
                $msg = $e->getMessage();

            }
            if ($res) {
                $msg = '活动创建成功';
            } else {
                $code = '536';
                $msg = '活动创建失败' . $msg;
            }
        }
        $this->helpJsonResult($code, $msg , $res);
        exit;
    }

    //修改活动
    public function eidt_raffle(){
        $aid = I('get.aid');
        if($aid<1){
            $this->helpJsonResult("活动id有误");
        }
        $Raffle = new \AuctionCore\Other\Raffle();
        if (IS_POST) {
            $code = '200';
            $msg = 'SUCCESS';
            $eidt = array();
            $eidt['a_name'] = trim(I('post.rafflename'));
            $eidt['amount'] = trim(I('post.amount'));
            $eidt['starttime'] = trim(I('post.start_date'));
            $eidt['endtime'] = trim(I('post.end_date'));
            $eidt['branch_id'] = trim(I('post.bc_city'));
            $eidt['type'] = trim(I('post.type'));
            $eidt['form'] = trim(I('post.form'));
            if ($eidt['type'] == 2) {
                $eidt['coupon_end_date'] = trim(I('post.coupon_end_date'));
            }
            $eidt['modifytime'] = date('Y-m-d H:i:s');
            $is_exist = M('activity')->where("a_name='$eidt[a_name]' and aid !='$aid'")->find();
            if (!empty($is_exist)) {
                $code = '536';
                $msg = '活动名称已存在';
            }
            //一个时间段只能存在一个活动
            $where = "((`starttime`>= '".$eidt['starttime']."' and `starttime` <= '".$eidt['endtime']."') or (`endtime` >='".$eidt['starttime']."' and `endtime`<= '".$eidt['endtime']."') or (`starttime`<= '".$eidt['starttime']."' and `endtime` >= '".$eidt['endtime']."')) and `type` = '".$eidt['type']."'  and `branch_id` = '".$eidt['branch_id']."' and aid !='".$aid."' "; 
            $is_exist1 = M('activity')->where($where)->find();
            if (!empty($is_exist1)) {
                $code = '537';
                $msg = '当前时间范围内已存在另外一个活动';
            }
            if ($code == '200') {
                try {
                    $res = $Raffle->update_one($eidt,$aid); //修改
                } 
                catch (AuctionException $e) {
                    $code = $e->getCode();
                    $msg = $e->getMessage();
                }
                if ($res) {
                    $msg = '活动修改成功';
                } else {
                    $code = '500';
                    $msg = '活动修改失败' . $msg;
                }
            }
            $this->helpJsonResult($code, $msg);
            exit;
        }
        $info = $Raffle->search_one($aid);
        $info['type1'] = $info['type'];
        echo json_encode($info);

    }

    //设置活动对应的卡券
    public function set_raffle_card($aid){
        $aid = I('get.aid');
        if($aid<1){
            $this->helpJsRedirect("活动id有误");
        }
        $allinfo = array();
        // $type = 1;
        $Raffle = new \AuctionCore\Other\Raffle();
        $group = $Raffle->get_num_balance($aid);
        //获取活动表中的面值限制
        $denomination = $Raffle->get_denomination($aid);
        //获取活动总面额
        $ac_info = $Raffle->search_one($aid);
        $allinfo = array(
            'group'=>$group,
            'denomination'=>$denomination,
            'amount'=>$ac_info['amount']
            );
        echo json_encode($allinfo);

    }
    /**
    *
     */
    public function get_build_card_log()
    {
        $aid = I('get.aid');
        if ($aid < 1)
        {
            $this->helpJsRedirect("活动id有误");
        }
        $Raffle = new \AuctionCore\Other\Raffle();
        $build_card_log = $Raffle->get_build_card_log($aid);
        echo json_encode($build_card_log);
    }

    /**
    *(新)生成活动奖券
     */
    public function build_card()
    {   
        $aid = I("post.ac_id");
        $denomination = I('post.price');
        $num = I('post.num');
        $createtime = I('post.createtime');
        if ($aid < 1)
        {
            $this->helpJsonResult("400","活动id有误");
        }
        $cards = [];
        $code = '200';
        $msg = 'SUCCESS';
        if (is_array($createtime)) {
            for ($i=0;$i<count($createtime);$i++){
                $cards[] = [
                    'aid'=>$aid,
                    'denomination'=>$denomination[$i],  
                    'num'=>$num[$i],
                    'emp_id'=>$this->emp_id,
                    'createtime'=>$createtime[$i]
                ];
            }
        }
        if (empty($cards)) {
            $this->helpJsonResult("401","请设置奖券");
        }
        try {
            $Raffle = new \AuctionCore\Other\Raffle();
            $ok = $Raffle->build_card($cards);
            if (!$ok)
            {
                $code = '400';
                $msg = '操作失败';
            }
        }
        catch (AuctionException $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        $this->helpJsonResult($code, $msg);
    }
    //生成活动卡券
    public function create_card(){
        $aid = I('get.aid');
        if($aid<1){
            $this->helpJsRedirect("活动id有误");
        }
        $code = '200';
        $msg = 'SUCCESS';
        $num = trim(I('post.num'));
        $price = trim(I('post.price'));
        try {
            $Raffle = new \AuctionCore\Other\Raffle();
            $ok = $Raffle->create_card($aid,$num,$price);
        } 
        catch (AuctionException $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        $this->helpJsonResult($code, $msg);
        exit;
    }

    //查看卡券列表
    public function card_list(){
        $aid = I('get.aid');
        if ($aid <1) {
            $this->helpJsRedirect("活动id有误");
        }
        $this->assign('aid', $aid); 
        $this->display();
    }

    public function get_card_list(){
        $p = I('request.p/d', 1);
        $p = $p < 2 ? 1 : $p;
        $limit = 10;
        //搜索条件
        $aid = I('get.aid');
        if ($aid <1) {
            $this->helpJsRedirect("活动id有误");
        }
        $status = trim(I('get.status'));
        $start_time = trim(I('get.start_time'));
        $end_time = trim(I('get.end_time'));
        $state = trim(I('get.s_status'));
        $use_state = trim(I('get.s_use_status'));
        $search_key = trim(I('get.search_key'));
        if ($state == '已抽奖') {
            $state1 = 1;
        }elseif ($state == '未抽奖') {
            $state1 = 0;
        }else{
            $state1 = '';
        }
        if ($use_state == '已使用') {
            $use_state1 = 1;
        }elseif ($use_state == '未使用') {
            $use_state1 = 0;
        }else{
            $use_state1 = '';
        }
        $params['aid'] = $aid;
        $params['status'] = $status;
        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        $params['state'] = $state1;
        $params['use_state'] = $use_state1;
        $params['search_key'] = $search_key;
        $du = new \AuctionCore\Other\RaffleList();
        if ($params['status'] == 1 || $params['status'] == 3) {
             $result = $du->not_gave_card_list($p, $limit, $params);
        }elseif ($params['status'] == 2) {
             $result = $du->gave_card_list($p, $limit, $params);
        }
        $list = empty($result['list']) ?: $result['list'];
        $this->assign('list', $list);
        $this->assign('params', $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $limit, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); 
        //模板赋值
        $this->assign('page', $show); 
        $this->assign('state', $state); 
        $this->assign('use_state', $use_state); 
        $this->display();
    }

    // //根据订单找到对应卡券面值
    // public function find_order_card($order_id){
    //     if ($aid <1) {
    //         $this->helpJsRedirect("订单id不存在");
    //     }
    //     $type = 1;
    //     $Raffle = new \AuctionCore\Other\Raffle($type);
    //     $face_value = $Raffle->find_order_card($order_id);
    //     return $face_value;
    // }


}